# edited by levi    @触摸按钮

#   Button类：
# • 封装了按钮的属性（如标签、位置、大小、颜色）和方法（如绘制按钮、判断是否被按下）
# • 如果没有指定按钮的宽度和高度，会根据标签的大小自动计算。

#   UI类:
# • 封装了主程序的逻辑，包括触摸屏、屏幕显示和按钮管理
# • 提供了   add_button   方法，方便动态添加按钮。

#   使用方法：调用   app.add_button   方法来添加新按钮。例如：ui.add_button("New Button", 50, 50, 100, 30)  （x坐标，y坐标，宽度，高度，颜色）
#   按钮按下后的逻辑在UI类 run方法里面自行编写。例如：if button.label == "New Button": print("New Button clicked!")

from maix import touchscreen, app, display, image

class Button:
    def __init__(self, label, x, y, width=None, height=None, color=image.COLOR_WHITE):
        self.label = label
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.color = color
        self.size = image.string_size(label)
        if width is None:
            self.width = 8 * 2 + self.size.width()
        if height is None:
            self.height = 12 * 2 + self.size.height()

    def draw(self, img):
        img.draw_rect(self.x, self.y, self.width, self.height, self.color, 2)
        img.draw_string(self.x + 8, self.y + 12, self.label, self.color)

    def is_pressed(self, x, y):
        return (self.x <= x <= self.x + self.width and
                self.y <= y <= self.y + self.height)

class UI:
    def __init__(self):
        self.ts = touchscreen.TouchScreen()
        self.disp = display.Display()
        self.img = image.Image(self.disp.width(), self.disp.height())
        self.img.draw_rect(0, 0, self.img.width(), self.img.height(), image.COLOR_WHITE)
        self.buttons = []

    def add_button(self, label, x, y, width=None, height=None, color=image.COLOR_WHITE):
        btn = Button(label, x, y, width, height, color)
        btn.draw(self.img)
        self.buttons.append(btn)

    def run(self):
        while not app.need_exit():
            x, y, pressed = self.ts.read()
            if pressed:
                for button in self.buttons:
                    if button.is_pressed(x, y):
                        if button.label == "< Exit":
                            app.set_exit_flag(True)
                        # 可以在这里添加更多按钮的逻辑
                        if button.label == "test":
                            print("test pressed!")
                        break

            # 将屏幕坐标映射回图像坐标
            x, y = image.resize_map_pos_reverse(self.img.width(), self.img.height(), self.disp.width(), self.disp.height(), image.Fit.FIT_CONTAIN, x, y)
            if pressed:
                self.img.draw_circle(x, y, 1, image.Color.from_rgb(255, 255, 255), 2)
            self.disp.show(self.img, fit=image.Fit.FIT_CONTAIN)


if __name__ == "__main__":
    ui = UI()
    ui.add_button("< Exit", 0, 0)
    ui.add_button("test", 100, 100) #创建按钮例子
    ui.add_button("Levi_jia", 250, 250, color=image.COLOR_RED)
    ui.run()
